package com.fingard.dsp.bank.directbank.fxb01;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.ParserConfig;
import com.fingard.FGBiz;
import com.fingard.constant.Format;
import com.fingard.db.JDBCHelper;
import com.fingard.dsp.bank.directbank.bankInterface.ISinglePay;
import com.fingard.dsp.bank.directbank.fxb01.util.MACUtil;
import com.fingard.dsp.bank.reqrespobj.balance.Req7506BalQry;
import com.fingard.dsp.bank.reqrespobj.balance.detail.RetAtsBalDetail;
import com.fingard.dsp.bank.reqrespobj.single.*;
import com.fingard.dsp.bank.reqrespobj.single.detail.RetAtsSglDetail;
import com.fingard.text.StringHelper;
import com.fingard.util.DateHelper;
import com.fingard.xml.XmlTextReader;

import java.io.File;
import java.sql.Connection;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

public class FXB01SinglePay extends FXB01Base implements ISinglePay {

    @Override
    public RetAtsSingle d_1908_SglPay(ReqSingle p_req1908) throws Exception {
        RetAtsSingle retAts = new RetAtsSingle(p_req1908.reqHeader);
        RetAtsSglDetail tmpRetAtsDetail = new RetAtsSglDetail();
        Connection conn = null;
        boolean isSendToBank = true;
        //跨行
        if (p_req1908.reqHeader.commandCode != null && "190801".equals(p_req1908.reqHeader.commandCode)) {
            try {
                JSONObject request = new JSONObject();
                JSONObject appHeader = new JSONObject();
                JSONObject body = new JSONObject();
                FXB01Header header = new FXB01Header();
                header.transCode = "300410004";
                header.clientTime = Format.DateTime2Format.format(new Date());
                header.batchID = p_req1908.reqHeader.transSeqID;
                header.pageSize = "1";
                body.put("TRAN_METHOD","1"); //1-实时 2-普通延时 3-次日延时
                body.put("SOURCE_SYS", this.getBankConfig().getValueAsString("sourceSystem"));//系统来源
                body.put("PAYER_ACCT_NO", p_req1908.singleDetail.payAct);
                body.put("PAYER_NAME", p_req1908.singleDetail.payName);
                body.put("PAYER_ADDR", p_req1908.singleDetail.payAreaName);
                body.put("TRAN_CCY", this.getBankConfig().getMapValueByKey("currencyMapping", p_req1908.singleDetail.payCur));
                body.put("AMT", p_req1908.singleDetail.payAmount);
                body.put("PAYEE_ACCT_NO", p_req1908.singleDetail.recAct);
                body.put("PAYEE_NAME", p_req1908.singleDetail.recName);
                body.put("PAYEE_ADDR", p_req1908.singleDetail.recAreaName);
                body.put("SYS_TP_T",p_req1908.singleDetail.payType);
                body.put("RCV_BANK_BANK_NO", p_req1908.singleDetail.recBankCode);
                body.put("RCV_BANK_NAME", p_req1908.singleDetail.recBankName);
                body.put("POSTSCRIPT", p_req1908.singleDetail.transInfo);
                body.put("WITHDRAWAL_TYPE", "w"); //支取方式
                body.put("PASSWORD", "");
                body.put("ACTUAL_PAYER_ACCT_TP", p_req1908.singleDetail.isPrivate);//0-内部账 1-对私 2-对公
                body.put("FEE_AMT", ""); //费用金额
                body.put("FEE_TYPE", this.getBankConfig().getValueAsString("feeType"));//费用类型
                request.put("APP_HEAD", appHeader);
                //机构号查询
                String branchId = getBranchIdByAcc(p_req1908);
                WriteBankLogLn("获取到的机构号为：" + branchId);
                if (StringHelper.isNullOrEmpty(branchId)) {
                    tmpRetAtsDetail.respCode = "-1";
                    tmpRetAtsDetail.respInfo = "查询账户的机构号失败";
                    retAts.writeRetDetail(tmpRetAtsDetail);
                    return retAts;
                }
                header.branchId = branchId;
                //MAC签名
                String filePath = FGBiz.dspCenter.rootDirPath + File.separator + "config" + File.separator + "portfiles" + File.separator + "FXB01" + File.separator + "server.conf";
                String MAC = MACUtil.getMAC(body.toJSONString(), "QYGL", "qyglToesb", "RZAK", filePath);
                header.MAC = MAC;
                writeCommonHeader(request, header);
                request.put("BODY", body);

                String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                try {
                    conn = FGBiz.getLocalDbConn();
                } catch (Exception e) {
                    isSendToBank = false;
                }


                String[] tmpStrRet = sendToBank(request.toJSONString(), p_req1908.reqHeader.transType, p_req1908.reqHeader.commandCode);
                if (tmpStrRet[0].length() == 0) {
                    StringBuilder tmpSbMsg = new StringBuilder();
                    JSONObject reponse = JSONObject.parseObject(tmpStrRet[1]);
                    if (reponse != null) {
                        JSONObject tmpHeader = JSONObject.parseObject(reponse.getString("SYS_HEAD"));
                        JSONArray ret = JSONArray.parseArray(tmpHeader.getString("RET"));
                        if (ret != null && ret.size() > 0) {
                            JSONObject object = JSONObject.parseObject(ret.get(0).toString());
                            String tmprspmsg = object.getString("RET_MSG");
                            String tmprspcod = object.getString("RET_CODE");
                            if (tmprspcod != null) {
                                JSONObject tmpBody = JSONObject.parseObject(reponse.getString("BODY"));
                                if (tmpBody != null) {
                                    JDBCHelper.update(conn, INSERTRECEIPT, new Object[]{uuid, p_req1908.reqHeader.bankCode, p_req1908.singleDetail.askNumber, tmpBody.getString("SYSTEM_REFERENCE") + "#" + p_req1908.singleDetail.payType, DateHelper.convertDateTimetoD8(p_req1908.singleDetail.payDate)});
                                }
                                tmpRetAtsDetail.respCode = "0";
                                tmpRetAtsDetail.respInfo = tmprspmsg;
                                tmpRetAtsDetail.reqSeqID = p_req1908.singleDetail.askNumber;
                                tmpRetAtsDetail.transState = p_req1908.reqHeader.commandCode + "+" + tmprspcod;
                                tmpRetAtsDetail.payInfoCode = tmprspcod;

                            } else {
                                tmpRetAtsDetail.respCode = "-1";
                                tmpRetAtsDetail.respInfo = tmprspmsg;

                            }
                        } else {
                            tmpRetAtsDetail.respCode = "-1";
                            tmpRetAtsDetail.respInfo = tmpHeader.getString("RET_MSG");
                        }
                    } else {
                        tmpRetAtsDetail.respCode = "-1";
                        tmpRetAtsDetail.respInfo = "银行返回错误";
                    }
                } else {
                    tmpRetAtsDetail.respCode = "-1";
                    tmpRetAtsDetail.respInfo = tmpStrRet[1];
                }
            } catch (Exception e) {
                retAts.writeRespCode("-1");
                retAts.writeRespInfo("单笔跨行转账异常，详情请查看DSP日志！");
                WriteBankLogLn("单笔转账异常:" + e.getMessage());
            } finally {
                if (conn != null) {
                    conn.close();
                }
                if (!isSendToBank) {
                    tmpRetAtsDetail.respCode = "0";
                    tmpRetAtsDetail.respInfo = "发送前流水号落库失败，未发送支付请求，请跟银行确认结果后手工处理";
                    tmpRetAtsDetail.reqSeqID = p_req1908.singleDetail.askNumber;
                    retAts.writeRetDetail(tmpRetAtsDetail);
                    return retAts;
                }
            }
        } else {
        try {
            JSONObject request = new JSONObject();
            JSONObject appHeader = new JSONObject();
            JSONObject body = new JSONObject();
            FXB01Header header = new FXB01Header();
            header.transCode = "300110001";
            header.clientTime = Format.DateTime2Format.format(new Date());
            header.batchID = p_req1908.reqHeader.transSeqID;
            header.pageSize = "1";
            body.put("BASE_ACCT_NO", p_req1908.singleDetail.payAct);
            body.put("ACCT_NAME", p_req1908.singleDetail.payName);
            body.put("TRAN_TYPE", "CM10");
            body.put("TRAN_CCY", this.getBankConfig().getMapValueByKey("currencyMapping", p_req1908.singleDetail.payCur));
            body.put("TRAN_AMT", p_req1908.singleDetail.payAmount);
            body.put("SETTLEMENT_DATE", Format.Date8Format.format(new Date()));
            body.put("COLLATE_FLAG", "Y"); //Y-参与对账 N-不参与对账
            body.put("OTH_BASE_ACCT_NO", p_req1908.singleDetail.recAct);
            body.put("OTH_BASE_ACCT_NAME", p_req1908.singleDetail.recName);
            body.put("OTH_BANK_NAME", p_req1908.singleDetail.recBankName);
            body.put("OTH_BANK_CODE", p_req1908.singleDetail.recBankCode);
            body.put("NARRATIVE", p_req1908.singleDetail.purpose);
            body.put("CHANNEL_TYPE", "CM");//标识大额，小额，银联等
            body.put("TRAN_METHOD", "01"); //01-实时到账02-次日到账03-延时到账
            body.put("CHARGE_MODE", "T");//C-现金收取 T-转帐收取 N-暂不收取 P-套餐内抵用
            request.put("APP_HEAD", appHeader);
            //机构号查询
            String branchId = getBranchIdByAcc(p_req1908);
            WriteBankLogLn("获取到的机构号为：" + branchId);
            if (StringHelper.isNullOrEmpty(branchId)) {
                tmpRetAtsDetail.respCode = "-1";
                tmpRetAtsDetail.respInfo = "查询账户的机构号失败";
                retAts.writeRetDetail(tmpRetAtsDetail);
                return retAts;
            }
            header.branchId = branchId;
            //MAC签名
            String filePath = FGBiz.dspCenter.rootDirPath + File.separator + "config" + File.separator + "portfiles" + File.separator + "FXB01" + File.separator + "server.conf";
            String MAC = MACUtil.getMAC(body.toJSONString(), "QYGL", "qyglToesb", "RZAK", filePath);
            header.MAC = MAC;
            writeCommonHeader(request, header);
            request.put("BODY", body);

            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            try {
                conn = FGBiz.getLocalDbConn();
            } catch (Exception e) {
                isSendToBank = false;
            }

            String[] tmpStrRet = sendToBank(request.toJSONString(), p_req1908.reqHeader.transType, p_req1908.reqHeader.commandCode);
            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                JSONObject reponse = JSONObject.parseObject(tmpStrRet[1]);
                if (reponse != null) {
                    JSONObject tmpHeader = JSONObject.parseObject(reponse.getString("SYS_HEAD"));
                    JSONArray ret = JSONArray.parseArray(tmpHeader.getString("RET"));
                    if (ret != null && ret.size() > 0) {
                        JSONObject object = JSONObject.parseObject(ret.get(0).toString());
                        String tmprspmsg = object.getString("RET_MSG");
                        String tmprspcod = object.getString("RET_CODE");
                        if (tmprspcod != null) {
                            JSONObject tmpBody = JSONObject.parseObject(reponse.getString("BODY"));
                            if (tmpBody != null) {
                                JDBCHelper.update(conn, INSERTRECEIPT, new Object[]{uuid, p_req1908.reqHeader.bankCode, p_req1908.singleDetail.askNumber, tmpBody.getString("REFERENCE"), DateHelper.convertDateTimetoD8(p_req1908.singleDetail.payDate)});
                            }
                            tmpRetAtsDetail.respCode = "0";
                            tmpRetAtsDetail.respInfo = tmprspmsg;
                            tmpRetAtsDetail.reqSeqID = p_req1908.singleDetail.askNumber;
                            tmpRetAtsDetail.transState = p_req1908.reqHeader.commandCode + "+" + tmprspcod;
                            tmpRetAtsDetail.payInfoCode = tmprspcod;

                        } else {
                            tmpRetAtsDetail.respCode = "-1";
                            tmpRetAtsDetail.respInfo = tmprspmsg;

                        }
                    } else {
                        tmpRetAtsDetail.respCode = "-1";
                        tmpRetAtsDetail.respInfo = tmpHeader.getString("RET_MSG");
                    }
                } else {
                    tmpRetAtsDetail.respCode = "-1";
                    tmpRetAtsDetail.respInfo = "银行返回错误";
                }
            } else {
                tmpRetAtsDetail.respCode = "-1";
                tmpRetAtsDetail.respInfo = tmpStrRet[1];
            }
        } catch (Exception e) {
            retAts.writeRespCode("-1");
            retAts.writeRespInfo("单笔同行转账异常，详情请查看DSP日志！");
            WriteBankLogLn("单笔转账异常:" + e.getMessage());
        } finally {
            if (conn != null) {
                conn.close();
            }
            if (!isSendToBank) {
                tmpRetAtsDetail.respCode = "0";
                tmpRetAtsDetail.respInfo = "发送前流水号落库失败，未发送支付请求，请跟银行确认结果后手工处理";
                tmpRetAtsDetail.reqSeqID = p_req1908.singleDetail.askNumber;
                retAts.writeRetDetail(tmpRetAtsDetail);
                return retAts;
            }
        }
    }
        retAts.writeRetDetail(tmpRetAtsDetail);
        return retAts;
    }

    @Override
    public RetAtsSingle d_1944_QrySglPay(ReqQrySingle p_req1944) throws Exception {
        RetAtsSingle retAts = new RetAtsSingle(p_req1944.reqHeader);
        RetAtsSglDetail tmpRetAtsDetail = new RetAtsSglDetail();
        Connection conn = null;
        JSONObject request = new JSONObject();
        JSONObject appHeader = new JSONObject();
        JSONObject body = new JSONObject();
        try {
            FXB01Header fuxin01Header = new FXB01Header();
            fuxin01Header.transCode = "300430001";
            fuxin01Header.clientTime = Format.DateTime2Format.format(new Date());
            fuxin01Header.batchID = p_req1944.reqHeader.transSeqID;
            fuxin01Header.pageSize = "1";
            fuxin01Header.branchId = bankFront.org;
            conn = FGBiz.getLocalDbConn();
            Map<String, Object> map = JDBCHelper.execQuerySingle(conn, SELECTRECEIPT, new Object[]{p_req1944.askNumber, p_req1944.reqHeader.bankCode});
            if (map == null || map.size() == 0) {
                tmpRetAtsDetail.respCode = "-1";
                tmpRetAtsDetail.respInfo = "没有这条请求映射的流水号！";
                retAts.writeRetDetail(tmpRetAtsDetail);
                return retAts;
            }
            /*
            String REFERENCE = map.get("BANKREQSEQID").toString();
            if(StringHelper.hasAnyChar(REFERENCE) && REFERENCE.contains("#")){
                String[] str = REFERENCE.split("#");
                body.put("REFERENCE", str[0]);
                if(str.length>=2){
                    fuxin01Header.branchId = str[1];
                }
            }else{
                tmpRetAtsDetail.respCode = "-1";
                tmpRetAtsDetail.respInfo = "获取映射流水号错误";
                retAts.writeRetDetail(tmpRetAtsDetail);
                return retAts;
            }*/
            if("190801".equals(p_req1944.reqHeader.commandCode)){
                body.put("ORIG_CHANNEL_DATE",map.get("TRANSDATE").toString());
                String[] reqStr = map.get("BANKREQSEQID").toString().split("#");
                if(reqStr.length > 1){
                    body.put("ORIG_CHANNEL_SEQ_NO",reqStr[0]);
                    body.put("ORIG_SYS_ID", reqStr[1]);
                } else {
                    tmpRetAtsDetail.respCode = "-1";
                    tmpRetAtsDetail.respInfo = "获取映射流水信息错误";
                    retAts.writeRetDetail(tmpRetAtsDetail);
                    return retAts;
                }
            } else {
                body.put("CHANNEL_TYPE", "CM");
                body.put("REFERENCE", map.get("BANKREQSEQID").toString());
                body.put("CHANNEL_SEQ_NO", "");
            }
            //MAC签名
            String filePath = FGBiz.dspCenter.rootDirPath + File.separator + "config" + File.separator + "portfiles" + File.separator + "FXB01" + File.separator + "server.conf";
            String MAC = MACUtil.getMAC(body.toJSONString(), "QYGL", "qyglToesb", "RZAK", filePath);
            fuxin01Header.MAC = MAC;
            writeCommonHeader(request, fuxin01Header);
            request.put("APP_HEAD", appHeader);
            request.put("BODY", body);
            String[] tmpStrRet = sendToBank(request.toJSONString(), p_req1944.reqHeader.transType, p_req1944.reqHeader.commandCode);
            if (tmpStrRet[0].length() == 0) {
                JSONObject reponse = JSONObject.parseObject(tmpStrRet[1]);
                if (reponse != null) {
                    JSONObject tmpHeader = JSONObject.parseObject(reponse.getString("SYS_HEAD"));
                    JSONArray ret = JSONArray.parseArray(tmpHeader.getString("RET"));
                    if (ret != null && ret.size() > 0) {
                        JSONObject object = JSONObject.parseObject(ret.get(0).toString());
                        String tmprspmsg = object.getString("RET_MSG");
                        String tmprspcod = object.getString("RET_CODE");
                        if (tmprspcod != null && "000000".equals(tmprspcod)) {
                            JSONObject tmpBody = JSONObject.parseObject(reponse.getString("BODY"));
                            if("190801".equals(p_req1944.reqHeader.commandCode)){
                                String reqStatus = tmpBody.getString("TRAN_STATUS");
                                if(reqStatus!=null){
                                    tmpRetAtsDetail.respCode = "0";
                                    tmpRetAtsDetail.respInfo = tmprspmsg;
                                    tmpRetAtsDetail.reqSeqID = p_req1944.askNumber;
                                    String tmpTransAmt = tmpBody.getString("TRAN_AMT");
                                    tmpRetAtsDetail.transAmt = StringHelper.isNullOrEmpty(tmpTransAmt) ? "0.00" : tmpTransAmt;
                                    tmpRetAtsDetail.transState = p_req1944.reqHeader.commandCode + "+" + reqStatus;
                                    tmpRetAtsDetail.payInfoCode = tmpRetAtsDetail.transState;
                                } else {
                                    tmpRetAtsDetail.respCode = "0";
                                    tmpRetAtsDetail.respInfo = tmprspmsg;
                                    tmpRetAtsDetail.reqSeqID = p_req1944.askNumber;
                                    tmpRetAtsDetail.transState = p_req1944.reqHeader.commandCode + "+" + tmprspcod;
                                    tmpRetAtsDetail.payInfoCode = tmpRetAtsDetail.transState;
                                }
                            } else {
                                if (tmpBody != null) {
                                    tmpRetAtsDetail.respCode = "0";
                                    tmpRetAtsDetail.respInfo = tmprspmsg;
                                    tmpRetAtsDetail.reqSeqID = p_req1944.askNumber;
                                    String tmpTransAmt = tmpBody.getString("TRAN_AMT");
                                    tmpRetAtsDetail.transAmt = StringHelper.isNullOrEmpty(tmpTransAmt) ? "0.00" : tmpTransAmt;
                                    tmpRetAtsDetail.transState = p_req1944.reqHeader.commandCode + "+" + tmprspcod;
                                    tmpRetAtsDetail.payInfoCode = tmpRetAtsDetail.transState;
                                } else {
                                    tmpRetAtsDetail.respCode = "0";
                                    tmpRetAtsDetail.respInfo = tmprspmsg;
                                    tmpRetAtsDetail.reqSeqID = p_req1944.askNumber;
                                    tmpRetAtsDetail.transState = tmprspcod;
                                    tmpRetAtsDetail.payInfoCode = tmpRetAtsDetail.transState;
                                }
                            }
                        } else {
                            tmpRetAtsDetail.respCode = "0";
                            tmpRetAtsDetail.respInfo = tmprspmsg;
                            tmpRetAtsDetail.reqSeqID = p_req1944.askNumber;
                            tmpRetAtsDetail.transState = p_req1944.reqHeader.commandCode + "+" + tmprspcod;
                            tmpRetAtsDetail.payInfoCode = tmpRetAtsDetail.transState;
                        }
                    } else {
                        tmpRetAtsDetail.respCode = "-1";
                        tmpRetAtsDetail.respInfo = tmpHeader.getString("RET_MSG");
                    }
                } else {
                    tmpRetAtsDetail.respCode = "-1";
                    tmpRetAtsDetail.respInfo = "银行返回错误";
                }
            } else {
                tmpRetAtsDetail.respCode = "-1";
                tmpRetAtsDetail.respInfo = tmpStrRet[1];
            }
        } catch (Exception e) {
            tmpRetAtsDetail.respCode = "-1";
            tmpRetAtsDetail.respInfo = "跨行转账结果查询出现异常，详情查看日志";
            WriteBankLogLn("跨行转账结果查询出现异常:" + e.getMessage());
            e.printStackTrace();
        } finally {
            if (conn != null) {
                conn.close();
            }
        }
        retAts.writeRetDetail(tmpRetAtsDetail);
        return retAts;
    }

    @Override
    public RetAtsSingleBat d_1908BAT_SglBatPay(ReqSingleBat p_req1908BAT) throws Exception {
        return null;
    }

    @Override
    public RetAtsSingleBat d_1944BAT_QrySglBatPay(ReqQrySingleBat p_req1944BAT) throws Exception {
        return null;
    }

    private String getBranchIdByAcc(ReqSingle p_req1908) throws Exception {
        WriteBankLogLn("开始执行机构号查询。。。。。。");
        String branchId = "";
        JSONObject request = new JSONObject();
        JSONObject appHeader = new JSONObject();
        JSONObject body = new JSONObject();
        FXB01Header tjcb01Header = new FXB01Header();
        tjcb01Header.transCode = "300130002";
        tjcb01Header.clientTime = Format.DateTime2Format.format(new Date());
        tjcb01Header.batchID = p_req1908.reqHeader.transSeqID;
        tjcb01Header.pageSize = "1";
        tjcb01Header.branchId = bankFront.org;
        //发银行报文的XML对象
        writeCommonHeader(request, tjcb01Header);
        request.put("APP_HEAD", appHeader);
        body.put("BASE_ACCT_NO", p_req1908.singleDetail.payAct);
        request.put("BODY", body);

        String[] tmpStrRet = sendToBank(request.toJSONString(), p_req1908.reqHeader.transType, p_req1908.reqHeader.transType);
        WriteBankLogLn("机构号查询返回的报文为：" + tmpStrRet[1]);
        if (tmpStrRet[0].length() == 0) {
            JSONObject reponse = JSONObject.parseObject(tmpStrRet[1]);
            if (reponse != null) {
                JSONObject tmpHeader = JSONObject.parseObject(reponse.getString("SYS_HEAD"));
                JSONArray ret = JSONArray.parseArray(tmpHeader.getString("RET"));
                if (ret != null && ret.size() > 0) {
                    JSONObject object = JSONObject.parseObject(ret.get(0).toString());
                    String tmprspmsg = object.getString("RET_MSG");
                    String tmprspcod = object.getString("RET_CODE");
                    if (tmprspcod != null && "000000".equals(tmprspcod)) {
                        JSONObject tmpBody = JSONObject.parseObject(reponse.getString("BODY"));
                        branchId = tmpBody.getString("BRANCH");
                    }
                }
            }
        }
        return branchId;
    }
}
